/* Constants */
var ut_k={
		metadata:"_md", 
		prefix: "CS:"
};
		
/* Configuration */
var ut_config={
	job_mappings: {
		"Default Implementation": function() {
				_md.beacon.jobs.push(["omni",ut_dynamicAccount("dev|pro","saccounterror"), ut_basicOmniConfig,"omniconfig|omnibasic"]);
				// _md.beacon.jobs.push(["ga",ut_dynamicAccount("dev|pro","saccounterror"), ut_basicGAConfig,"gaconfig" ]);
		},	
	},
	dynamic_accounts: {
		dev: [location.hostname, "localhost|firefly.iwright.org|re:stg\\.firefly\\d\\.iwright\\.org", function() {return ["saccounttest"];}],
		pro: [location.hostname, "vorpal.iwright.org", function() {return ["saccountpro"];}]
	},
	includes: ["../lib/sc/s_code.js"],
	
	variable_mappings: {
		omniconfig: { 
			charSet:"UTF-8",
			currencyCode:"USD",
			trackDownloadLinks:true,
			trackExternalLinks:true,
			trackInlineStats:true,
			linkDownloadFileTypes:"exe,zip,wav,mp3,mov,mpg,avi,wmv,doc,pdf,xls",
			linkInternalFilters:"javascript:,"+_getDomain(),
			linkLeaveQueryString:false,
			linkTrackVars:"None",
			linkTrackEvents:"None",
			visitorNamespace:"omniture",
			dc:"112",
		},
		omnibasic: {
			"_md.page.lastlink":"p:h_cm2",
			pageName:"m:page.name",
			prop7:"m:page.country",
			prop12:"m:metatags.web_section_id",	
			prop49:window.location.hostname + window.location.pathname,
			prop50:window.location.href,
			prop23:"q:search_result_type",
			eVar50:"s:prop48",
			prop45:"c:h_cm2",
			eVar13:"s:prop45",
			server:window.location.hostname.toLowerCase(),
			ut_prefix:_set
		},
	},
	
	event_mappings: {		
		eventbasic: {
			"Purchase":"purchase",
			"Internal Search":"event12",
			"Internal Search Clickthrough":"event13",
			"Value Lead: Download Trial":"event10",
			"Value Lead: Unqualified Lead":"event11",
			"Article Or Content Consumption":"event45"
		}	
	}
	
};

ut_doAnalyticsLogic();
function ut_doAnalyticsLogic() {
	if(ut_initTagLogic() ) {
		_prv_loadMetatags();
		if(ut_config.job_mappings[_md.type]!=null) ut_config.job_mappings[_md.type]();
		_prv_mapAtoF(ut_config.includes,ut_includeJavaScriptFile);
	}
}

function ut_dynamicAccount(configurations,defaultRS) {
	// Dynamic Account Settings
	var hpdynamic_accountmap=ut_config.dynamic_accounts;
	// Process Dynamic Accounts
	var rsArray=[],i,j,confs;
	rsArray.push(defaultRS);
	confs=configurations.split("|");
	for(i=0;i<confs.length;i++) {
		var am=hpdynamic_accountmap[confs[i]];
		var chk=am[0];
		var ma=am[1].split("|"),j;
		for(j=ma.length-1;j>=0;j--) {
			var m=ma[j];
			if( (m.indexOf("re:")==0 && (new RegExp(m.substr(3))).test(chk)) || (chk.indexOf(m)!=-1) ) { 
				rsArray=(typeof(am[2])=="function")?am[2]():am[2];
			}
		}		
	}
	return rsArray.join(",");
}


function ut_basicOmniConfig(autoconfig, s) {
	_prv_applyVariableMapping(autoconfig,s);
}
	
function ut_basicGAConfig(s) {
	/* GA basic Mapping */
}

function s_beacon_plugins() {
	return {
		"none": function() {
		},
		"omni": function() {
			var b=window._md.beacon.jobs;
			for(var i=b.length-1;i>-1;i--) {
				if(b[i][0]=="omni") {
					var s=s_gi(b[i][1]); // Get Omniture instance
					b[i][2](b[i][3],s); // Configure & Map Variables
					if(_md.beacon.override["linkTrackVars"]!=null) s.linkTrackVars=_md.beacon.override["linkTrackVars"];
					if(_md.beacon.override["linkTrackEvents"]!=null) s.linkTrackEvents=_md.beacon.override["linkTrackEvents"];
					var t = _md.beacon.attributes["type"];
					var n = _md.beacon.attributes["id"];
					if(t=="exit") s_code=s.tl(this,'e',n);
					else if(t=="download") s_code=s.tl(this,'d',n);
					else if(t=="link" || t=="datapass") s_code=s.tl(this,'o',n);
					else s_code=s.t();
					if(s_code)document.write(s_code);
					_md.beacon.override=[];
				}
			}
		},
		"ga": function() {
			var b=window._md.beacon.jobs;
			for(i=b.length-1;i>-1;i--) {
				if(b[i][0]=="ga") {
					var pageTracker = _gat._getTracker(b[i][1]); // get GA Instance
					b[i][2](b[i][3],s); // Configure & Map Variables
					pageTracker._trackPageview();
				}
			}
		}
	};
}

function s_beacon_repaint() //overrides should be defined in here.
{
	return {
		"none": function() {
		},
		"linkClick": function() {
			_md.ck.set("h_cm2",_md.beacon.attributes["id"]);
		},
		"promoClick": function() {
			_md.ck.set("h_cm2",_md.beacon.attributes["id"]);
		},
		"immediateLinkClick": function() {
			_md.beacon.showlib["omni"]();
		},
		"immediatePromoClick": function() {
			_md.beacon.showlib["omni"]();
		},
		"newPage": function() {
			_md.beacon.showlib["omni"]();
		}
	};
}

function ut_initTagLogic() {
	if(window._md) {
		if(window.ut_basicOmniConfig==null) {
			window.ut_basicOmniConfig=function (autoconfig, s) {
				_prv_applyVariableMapping(autoconfig,s);};
		}
		_md.ck={"get":function(k){var c=' '+document.cookie,s=c.indexOf(' '+k +'='),e=s<0?s:c.indexOf(';',s),v=s<0?'':c.substring(s+2 +k.length,e<0?c.length:e);return v},
			"set":function(k,v,e){var exp=new Date((new Date().getTime())+e*86400000); document.cookie=k+"="+escape(v)+ (e!=null?"; expires="+exp.toGMTString():"") +"; path=/; domain="+(ut_k.domain!=null?ut_k.domain:_getDomain());} };
		if(_md.beacon==null) {
			_md.beacon={"showlib":null, "jobs":[],"repaint":null,"attributes":[],"override":[],"wait":null};
			var map=new Array();
			_md.beacon.showlib=s_beacon_plugins();
			_prv_showBeacon=function(type,attri) {
				_md.beacon.attributes=attri;
				_md.beacon.showlib[type]();
			}
			_md.beacon.repaint=s_beacon_repaint();
		}
		return true;
	}
	return false;
}	
function trackMetrics(type,attri) {
	_md.beacon.attributes=attri;
	_md.beacon.repaint[type]();
}

/* START PACK CODE */
function ut_getQueryParam(name){  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  var regexS = "[\\?&]"+name+"=([^&#]*)";  var regex = new RegExp( regexS );  var results = regex.exec( window.location.href );  if( results == null )    return "";  else    return results[1];}

function _prv_applyVariableMapping(autoconfig,aobj) {
	var aca=autoconfig.split("|"),i,a,ai;
	for(i=aca.length-1;i>=0;i--) {
		ai=ut_config.variable_mappings[aca[i]];
		if(ai!=null) {
			var post=function(x){return x};
			if(typeof(ai["ut_prefix"])=="function") post=ai["ut_prefix"];
			for(a in ai) {
				try {
					var v=ai[a],t=v.substr(0,1),p1=v.substr(2),md=eval(ut_k.metadata),res=post(v);
					if(t=="m") res=post(eval(ut_k.metadata +"."+ p1));									// Access the data from the metadata object
					if(t=="q") res=post(ut_getQueryParam(p1));											// Query string parameter
					if(t=="s") res=aobj[p1];															// Use SiteCatalyst object variable
					if(t=="c") { res=post(md.ck.get(p1)); md.ck.set(p1,"-",-1); }						// Read cookie and clear
					if(t=="p") { res=post(md.ck.get(p1)); }												// Persistent cookie - do not clear
					if(a.indexOf(".")!=-1) eval(a+"='"+res+"'"); else aobj[a]=res; 						// If using a dot-notation, use eval statement
				} catch(x) {}
			} 
		}
	}
}

function _prv_loadMetatags() {
	if(!_md.metatags) {
		_md.metatags={};
		var mt=document.getElementsByTagName("meta"),i,mtt=_md.metatags,pg=_md.page;
		for(i=mt.length-1;i>=0;i--) {
			if(mt[i].name.length>0) _md.metatags[mt[i].name.toLowerCase()]=(mt[i].content?mt[i].content.toLowerCase():"");
		}
		_md.metatags.language=document.getElementsByTagName("html")[0].lang;
	}
}
function ut_includeJavaScriptFile(i_path) {
	d=document;ip=i_path;ssl=(window.location.protocol.toLowerCase().indexOf('https')!=-1);
	if(d.getElementsByTagName) {
		h=document.getElementsByTagName("body")[0];
		s=d.createElement("script");
		s.type='text/javascript';
		s.src=ip;
		h.appendChild(s);
	}
}
function _prv_mapAtoF(a,f) {
	try {var i;for(i=a.length-1;i>=0;i--){f(a[i]);} } catch(x){}; 
}
function _prv_getNthElement(val,i,delim,defaultVal) {
	var x=val.split(delim); return (i<=x.length-1?x[i]:defaultVal);
}
function _set(x) {
	return x!=null&&x.length>0?(ut_k.prefix?ut_k.prefix+x:x).toLowerCase():null;
}
function _getDomain() {
	ut_k.domain=window.location.hostname.split(".").splice(2).join(".");	
	return ut_k.domain;
}
function _prv_showBeacon(type) {}; 
/* END PACK CODE */
